from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.db.models import Max,Q,F,Min,Avg,Count,Sum
from django.contrib.auth.hashers import make_password,check_password
import datetime  #导入时间包
import time
import random
from utils.coom  import *

from .ser import *

# Create your views here.

class Cart111m(APIView):
    def get(self,request):
        cart = Cart111.objects.all()
        ser = Cart111mSer(cart,many=True)
        return Response({"code":200,'list':ser.data})


#注册
import re
class UserRegister(APIView):
    def post(self,request):
        #用户名
        username = request.data.get('username')
        if not username:
            return Response({"code":11000})
        if not re.match('^\w{5,10}$',username):
            return Response({"code": 11001})
        user = USerregister.objects.filter(username=username).first()
        if user == username:
            return Response({"code": 11002})
        return Response({"code":200})

        #密码
        password = request.data.get('password')
        if not password:
            return Response({"code": 11003})
        if not re.match('^\w{8,20}$', password):
            return Response({"code": 11004})

        #判断验证码
        veris = request.data.get('veris')
        # 1.链接
        coom = get_redis_conn()
        #2.获取
        yanz = coom.get(num)
        if veris:
            veriss = str(veris,encoding='utf8')
        if veriss == yanz:
            return Response({"code":11005})

        #注册添加
        ser = UserRegisterSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 20010})

        # return Response({"code": 200})

import redis
#验证码
class Verimanage(APIView):
    def post(self,request):
        # 验证码
        mobile = request.data.get('mobile')
        print(mobile)
        num = random.randint(1000, 9999)
        print(num)
        send_message(mobile, num, 1)
        # redis保存
        # 1.链接
        com = get_redis_conn()
        # # 2.保存
        com.setex(mobile,60,num)
        return Response({'code': 200})
